package ai;

import game.Game;

public abstract class Ai implements Runnable {

	//Reference to Game class
	protected Game game;
	
	//The side of the computer
	protected byte side;
	protected byte opponent;
	
	//Returns the columns where to insert a token
	protected abstract int getZet();
	
	//Thread variable to check if the thread should shut itself down
	private boolean keepRunning;
	
	//Constructor
	protected Ai(Game g, byte side)
	{
		this.game = g;
		this.side = side;
		
		if (side == Game.PLAYER1) {
			this.opponent = Game.PLAYER2;
		}
		else {
			this.opponent = Game.PLAYER1;
		}
		
		//Make sure the Thread actually starts
		this.keepRunning = true;
	}
	
	//Main function of the thread
	public void run()
	{
		//Shut yourself down if the game is finished
		while (this.isRunning())
		{
			if (this.game.getCurrentSide() == this.side && ! this.game.gameHasEnded())
			{
				try
				{
					Thread.sleep(10);
				}
				catch (InterruptedException ex)
				{
					ex.printStackTrace();
					return;
				}

				//Execution time
				long execTime = System.currentTimeMillis();
				
				//Calculate the best move
				int move = this.getZet();
				
				//Execution time
				execTime = System.currentTimeMillis() - execTime;
				System.out.println("Execution time in mili seconds: "+execTime);
				System.out.println("Execution time in seconds: "+execTime / 1000);
				
				//Check if we have been shutdown while we were calculating the move
				if (this.isRunning() && ! this.game.gameHasEnded())
				{
					//Play the move
					this.game.playGame(move);
				}
			}
			else
			{
				synchronized(this.game)
				{
					//Wait because it's not the computers turn yet
					try
					{
						this.game.wait();
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	
	private synchronized boolean isRunning()
	{
		return this.keepRunning;
	}
	
	//To shut a thread down
	public synchronized void shutdown()
	{
		this.keepRunning = false;
	}
	
	
	
	/*
	//Debug function to dump the array contents
	protected void printArray()
	{
		System.out.println();
		System.out.println("Contents of the array:");
		
		
		for(int j = 0; j < Game.YSIZE; j++)
		{
			for(int i = 0; i < Game.XSIZE; i++)
			{
				System.out.print(this.aiPlayingField[i][j]);
			}
			System.out.println();
		}
	}*/
	
	
}
